﻿// ParseLib - An open source library for natural language processing.
// Copyright (C) Kais Dukes, 2012. E-mail: kais@kaisdukes.com
// http://parselib.org

using System;
using System.Collections.Generic;

namespace ParseLib.Algorithms
{
    public static class Extensions
    {
        public static T ArgMax<T, TValue>(
            this IEnumerable<T> collection, Func<T, TValue> function)
            where TValue : IComparable<TValue>
        {
            return ArgMatch(collection, function, (a, b) => a.CompareTo(b) > 0);
        }

        public static T ArgMin<T, TValue>(
            this IEnumerable<T> collection, Func<T, TValue> function)
            where TValue : IComparable<TValue>
        {
            return ArgMatch(collection, function, (a, b) => a.CompareTo(b) < 0);
        }

        private static T ArgMatch<T, TValue>(
            IEnumerable<T> collection, Func<T, TValue> function, Func<TValue, TValue, bool> accept)
            where TValue : IComparable<TValue>
        {
            var first = true;
            var matchArg = default(T);
            var matchValue = default(TValue);

            foreach (var item in collection)
            {
                var value = function(item);
                if (!first && !accept(value, matchValue)) continue;
                matchArg = item;
                matchValue = value;
                first = false;
            }

            return matchArg;
        }
    }
}
